<template>
  <div class="trigger-list-setting" v-if="triggerGray">
    <div class="trigger-list-setting-header">
      <div class="trigger-list-setting-header-left">
        <div class="trigger-list-setting-header-title">
          {{ title }}
        </div>
        <div class="trigger-list-setting-header-sub-title">
          {{ subTitle }}
        </div>
      </div>
      <div class="trigger-list-setting-header-right">
        <el-button 
            type="primary" 
            @click="addTrigger"
          >
            <i class="iconfont icon-add2">
            </i>
            {{ $t('common.base.create') }}
          </el-button>
      </div>
    </div>
    <div class="trigger-list" v-if="list && list.length">
      <TriggerListItem
        v-for="item in list"
        :key="item.id"
        :value.sync="item"
        @edit="toEdit"
        @delete="toDelete"
        @update="toUpdate"
        @updateList="getList"
        :authType="authType"
      >
      </TriggerListItem>
    </div>

    <ConnectorListViewCreateDialog
        :title="formValue.id ? $t('common.connector.trigger.edit') : $t('common.connector.trigger.create')"
        :value="formValue"
        :visible="visible"
        :fields="CreateConnectorFields"
        @close="onDialogCloseHandler"
        @confirm="onDialogConfirmHandler"
        @input="onDialogUpdateHandler"
    >
    </ConnectorListViewCreateDialog>
    <CreateTriggerDialog
        ref='CreateTriggerDialog'
        @submit="onDialogSubmitHandler"
    >
    </CreateTriggerDialog>
  </div>
</template>
<script>
/* components */
import { ConnectorListViewCreateDialog } from '@src/modules/connector/view/list/components'
import CreateTriggerDialog from '@src/modules/trigger/components/CreateTriggerDialog'
import TriggerListItem from './components/item.vue'
/* api */
import * as TriggerApi from '@src/modules/connector/api/trigger'
import AuthUtil from '@src/util/auth';
/* util */
import { openAccurateTab } from '@src/util/platform'
// import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'
import { message, confirm } from '@src/util/message'
import { isFalse, isFalsy } from '@src/util/type'
import { getRootWindow } from '@src/util/dom'
/* enum */
import { AuthEnum } from "@src/modules/connector/model/enum"
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* model */
import { CreateConnectorFields } from '@src/modules/connector/view/list/model'
import { t } from '@src/locales'
export default {
  name:'trigger-list-setting',
  props:{
    title:{
      type:String,
      default: t('common.connector.title.trigger')
    },
    subTitle:{
      type:String,
      default: t('common.connector.trigger.create')
    },
    bizType:{
      type:String,
      default:''
    },
    bizTypeId:{
      type:String,
      default:''
    },
    bizActionCode:{
      type:String,
      default:''
    },
    bizActionName:{
      type:String,
      default:''
    }
  },
  computed:{
    listQuery(){
      return {
        bizType:this.bizType,
        bizTypeId:this.bizTypeId,
        bizActionCode:this.actionCode,
        pageNum:1,
        pageSize:9999
      }
    },
    triggerGray(){
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.TRIGGER || false;
    },
    newTriggerGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.NEW_TRIGGER || false;
    },
  },
  watch:{
    bizActionCode(newVal){
      this.init()
    }
  },
  data(){
    return{
      list:[],
      visible:false,
      CreateConnectorFields,
      formValue:{
        name:'',
        description:''
      },
      actionCode:'',
      authType: {
        isCreate: false,
        isDelete: false,
        isEdit: false
      },
      auth: {}
    }
  },
  mounted() {
    this.init()
  },
  created() {
    this.getAuthByRootInitData()
  },
  methods: {
    // 权限控制
    getAuthByRootInitData() {
      const rootWindow = getRootWindow(window)
      const _initData = JSON.parse(rootWindow?._init || '{}')
      this.auth = _initData?.user?.auth || {}
      this.authType.isCreate = AuthUtil.hasAuth(this.auth, AuthEnum.trigger_view);
      this.authType.isDelete = AuthUtil.hasAuth(this.auth, AuthEnum.trigger_delete);
      this.authType.isEdit = AuthUtil.hasAuth(this.auth, AuthEnum.trigger_edit);
    },
    addTrigger(){
      if (this.newTriggerGray) {
        this.$refs.CreateTriggerDialog.showDialog();
      } else {
        this.visible = true
      }
    },
    init(){
      
      if (!this.triggerGray) {
        return
      }
      this.list = []
      if(this.bizActionCode){
        TriggerApi.getTriggerFormInfo({
          "bizType": this.bizType,
          "bizTypeId":this.bizTypeId,
          "oldActionCode": this.bizActionCode
        }).then(res=>{
          if(res.status == 0){
            this.actionCode = res.data?.currActionCode?.bizActionCode || ''
            this.getList();
          }
        })
      }else{
        this.getList();
      }
    },
    getList(){
      TriggerApi.getTriggerInfoList(this.listQuery).then(res=>{
        if(res.status == 0){
          this.list = res.data?.list || []
        }else{
          console.error('error', `触发器列表获取失败：${res.message}`);
        }
      })
    },
    resetFormValue(){
      this.formValue = {
        name:'',
        description:''
      }
    },
    onDialogCloseHandler(){
      this.visible = false
      this.resetFormValue()
    },
    onDialogConfirmHandler(){
      if(this.formValue.id){
        TriggerApi.updateTriggerStat({triggerId: this.formValue.id,triggerName:this.formValue.name,triggerDesc:this.formValue.description}).then(res=>{
          if(res.status == 0){
            message.success(t('common.base.tip.modifySuccess'))
            this.getList()
            this.onDialogCloseHandler()
          }else{
            message.error(res.message)
          }
        })
      }else{
        let fromId = window.frameElement?.getAttribute('id');
        openAccurateTab({
          type: PageRoutesTypeEnum.PageConnectorSetting,
          params: `name=${this.formValue.name}&description=${this.formValue.description}&bizTypeId=${this.bizTypeId}&bizType=${this.bizType}&bizActionCode=${this.bizActionCode}`,
          fromId,
          reload:true
        })
        this.onDialogCloseHandler()
      }
    },
    onDialogUpdateHandler(info) {
      let { fieldName,newValue } = info
      if( !fieldName )return;
      this.formValue[fieldName] = newValue
    },
    toEdit(value){
      let fromId = window.frameElement?.getAttribute('id');
      if (this.newTriggerGray) {
				openAccurateTab({
					type: PageRoutesTypeEnum.PageTriggerDesign,
					params: `triggerId=${value.id}`,
					fromId
				})
			} else {
				openAccurateTab({
					type: PageRoutesTypeEnum.PageConnectorSetting,
          titleKey: value.triggerNo,
          key:value.id,
          params: `id=${value.id}`,
          fromId
				})
			}
    },
    async toDelete(value){
      const confirmed = await confirm.warning(t('common.connector.tips.tip1'))
      if (isFalsy(confirmed)) {
        return
      }
      TriggerApi.deleteTrigger(value.id).then(res=>{
        if(res.status===0){
          this.getList()
        }else{
          message.error(res.message)
        }
      })
    },
    toUpdate(value){
      this.formValue = {
        id:value.id,
        name:value.triggerName,
        description:value.triggerDesc
      }
      this.visible = true
    },
    onDialogSubmitHandler(formValue) {
      const fromId = window.frameElement.getAttribute('id') || ''
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTriggerDesign,
        params: `name=${formValue.value.name}&triggerWay=${formValue.value.triggerWay}&desc=${formValue.value.des}`,
        fromId
      })
      this.$refs.CreateTriggerDialog.closeDialog();
    },
  },
  components:{
    ConnectorListViewCreateDialog,
    TriggerListItem,
    CreateTriggerDialog,
  }
}
</script>
<style lang="scss">
@import './index.scss';
.trigger-list-item-part {  
  img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}
</style>